package com.foreveross.taskservice.web.controller.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.dayatang.domain.InstanceFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.foreveross.taskservice.application.statistics.EngineStatisticsHistoryApplication;
import com.foreveross.taskservice.application.task.statsdetail.ICrawlStatsApplication;
import com.foreveross.taskservice.application.task.statsdetail.vo.CrawlStatsVO;
import com.foreveross.taskservice.infra.util.DateUtil;
import com.foreveross.taskservice.web.controller.auth.BaseController;
import com.google.common.collect.Lists;

/**
 * 抓取统计
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/task/CrawlStats")
public class CrawlStatsController extends BaseController{
	@Resource(name="crawlStatsApplicationImpl")
	private ICrawlStatsApplication crawlStatsApplication;
//	@Resource(name ="EngineStatisticsHistoryApplication")
	@Inject 
	private EngineStatisticsHistoryApplication engineStatisticsHistoryApplication;
	
	@RequestMapping("/successRate")
	public String successRate(ModelMap modelMap,@RequestParam(required=false) String grabDateStr)throws Exception{
		String nowsday=DateUtil.getNowDateStr("yyyy-MM-dd");
		if(StringUtils.isBlank(grabDateStr)) grabDateStr = nowsday;
		List<CrawlStatsVO> vos = Lists.newArrayList();
		
		//测试mysql持久化
		/*List<CrawlStatsVO> vos2 =Lists.newArrayList();
		//List<CrawlStatsVO> vos=crawlStatsApplication.getAllChannelCrawlSuccessStats();
		vos2=InstanceFactory.getInstance(ICrawlStatsApplication.class).showAllChannelCrawlSuccessStats();
		if(vos2.size()>0){
			InstanceFactory.getInstance(EngineStatisticsHistoryApplication.class).addDataByDate(vos2);	
		}
		*/
		
		if(grabDateStr !=null && !grabDateStr.equals("") && !grabDateStr.equals(nowsday)){
			//历史数据(查询mysql)
			vos=engineStatisticsHistoryApplication.findVoByDate(grabDateStr);
		}else{
			//当前数据(查询redis)
			vos=crawlStatsApplication.showAllChannelCrawlSuccessStats();
		}
		modelMap.put("data", vos);
		modelMap.put("currentDates", getNearlyDays());//今天的日期
		modelMap.put("currentSelectDate", grabDateStr);//当前选择的日期
		return "task/crawlStats_successRate";
	}
	/**
	 * 获得最近的日期字符串集合
	 * <p>这里是一周,包括今天
	 * @return
	 */
	private List<String> getNearlyDays(){
		List<String> dates = new ArrayList<String>();
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, -6);
		for(int i=0 ;i < 7; i++){
			dates.add(DateUtil.formatDay(cal.getTime(), "yyyy-MM-dd"));
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		return dates;
	}
	
}
